public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        
        /*
        int[] visited = new int[n];

        int start = -1;
        for (int i = 1; i < n; i++) {
            int k = 0;
            while (k < m) {
                start = (start + 1) % n;
                if (visited[start] == 0) {
                    k++;
                }
                
            }
            visited[start] = 1;
            System.out.println(start);
        }

        for (int i = 0; i < n; i++) {
            if (visited[i] == 0) {
                return i;
            }
        }

        return -1;
        */

        // 约瑟夫环
        /*
        if (n == 1) {
            return 0;
        }

        return (LastRemaining_Solution(n - 1, m) + m) % n;
        */

        int value = 0;
        for (int i = 1; i <= n; i++) {
            value = (value + m) % i;
        }
        return value;


    }
}
